package com.github.anastr.speedview.slice;

import com.github.anastr.speedview.ResourceTable;
import com.github.anastr.speedviewlib.SpeedView;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RecyclerAbilitySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_recycler);

        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_listContainer);

        List<Integer[]> speeds = new ArrayList<>();
        for (int i=0; i<100; i++)
            speeds.add(new Integer[]{new Random().nextInt(99)+1,new Random().nextInt(99)+1});

        listContainer.setItemProvider(new ListProvider(speeds));
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }


    public class ListHolder{
        SpeedView speedometer1;
        SpeedView speedometer2;

        public ListHolder(Component component) {
            speedometer1 = (SpeedView) component.findComponentById(ResourceTable.Id_speedometer1);
            speedometer2 = (SpeedView) component.findComponentById(ResourceTable.Id_speedometer2);
        }
    }

    public class ListProvider extends BaseItemProvider {
        List<Integer[]> speeds;

        public ListProvider(List<Integer[]> speeds) {
            this.speeds = speeds;
        }

        @Override
        public int getCount() {
            return speeds.size();
        }

        @Override
        public Object getItem(int i) {
            return speeds.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
            final Component cpt;
            ListHolder holder;
            if (component == null) {
                cpt = LayoutScatter.getInstance(RecyclerAbilitySlice.this).parse(ResourceTable.Layout_item_recycler, null, false);
                holder = new ListHolder(cpt);
                cpt.setTag(holder);
            } else {
                cpt = component;
                holder = (ListHolder) cpt.getTag();
            }
            holder.speedometer1.speedTo(speeds.get(i)[0]);
            holder.speedometer2.speedTo(speeds.get(i)[1]);
            return cpt;
        }
    }

}
